project(xlog VERSION 1.0.0 LANGUAGES CXX)

# 包版本变量
set(XLOG_VERSION ${PROJECT_VERSION})

file(GLOB LIBSRC *.cpp)

add_library(xlog STATIC ${LIBSRC})

target_compile_definitions(xlog PUBLIC -DCONFIG_PATH=\"${CMAKE_CURRENT_LIST_DIR}\")

# 在构建时尽量使用 include/，若不存在则退回到当前源目录
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/include")
  set(XLOG_BUILD_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include")
else()
  set(XLOG_BUILD_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
endif()

target_include_directories(xlog
  PUBLIC
    $<BUILD_INTERFACE:${XLOG_BUILD_INCLUDE_DIR}>
    $<INSTALL_INTERFACE:include/xlog>
)

include(CMakePackageConfigHelpers)

# 安装库并导出 targets
install(TARGETS xlog
  EXPORT xlogTargets
  ARCHIVE DESTINATION lib
  LIBRARY DESTINATION lib
  RUNTIME DESTINATION bin
  INCLUDES DESTINATION include/xlog
)

# 导出 lib/xlog 目录下的所有头文件（保留目录结构）
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/
  DESTINATION include/xlog
  FILES_MATCHING
    PATTERN "*.h"
    PATTERN "*.hpp"
    PATTERN "*.inl"
)

# 生成并安装 CMake package 配置（用于 find_package）
set(CONFIG_INSTALL_DIR lib/cmake/xlog)

write_basic_package_version_file(
  "${CMAKE_CURRENT_BINARY_DIR}/xlogConfigVersion.cmake"
  VERSION ${XLOG_VERSION}
  COMPATIBILITY AnyNewerVersion
)

configure_package_config_file(
  "${CMAKE_CURRENT_LIST_DIR}/cmake/xlogConfig.cmake.in"
  "${CMAKE_CURRENT_BINARY_DIR}/xlogConfig.cmake"
  INSTALL_DESTINATION ${CONFIG_INSTALL_DIR}
)

install(FILES
  "${CMAKE_CURRENT_BINARY_DIR}/xlogConfig.cmake"
  "${CMAKE_CURRENT_BINARY_DIR}/xlogConfigVersion.cmake"
  DESTINATION ${CONFIG_INSTALL_DIR}
)

install(EXPORT xlogTargets
  FILE xlogTargets.cmake
  NAMESPACE xlog::
  DESTINATION ${CONFIG_INSTALL_DIR}
)

# 在构建树中也导出 targets（方便 CMAKE_PREFIX_PATH 指向构建目录时使用）
export(EXPORT xlogTargets FILE "${CMAKE_CURRENT_BINARY_DIR}/xlogTargets.cmake")
